package cn.janescott.inner.space.lib.boot.starter;

import cn.janescott.inner.space.lib.boot.properties.SpringBootAdminProperties;
import cn.janescott.inner.space.lib.web.filter.SpringBootAdminFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 基于springboot admin监控框架
 * 使用细则：
 * 需要引入相关依赖
 * 并且在配置文件中添加
 * me.springboot.admin.enabled=true
 * 用于对指定的ip地址开放endpoints
 * 由于springboot admin需要配置允许所有endpoints对外开发，
 * 为了防止被非法获取信息，所以添加此filter用于只对配置内的
 * ip和url无需权限的开发！
 * @date 2018/7/20
 * @author scott
 */
@Configuration
@ConditionalOnProperty(prefix = "me.springboot.admin", name = "enabled", havingValue = "true")
@EnableConfigurationProperties({SpringBootAdminProperties.class})
@AutoConfigureOrder(AutoConfigureOrder.DEFAULT_ORDER - 100)
public class SpringBootAdminFilterAutoConfiguration {

    private Logger logger = LoggerFactory.getLogger(getClass());

    //@see https://blog.csdn.net/king_is_everyone/article/details/75308620

    @Bean
    @ConditionalOnMissingBean({SpringBootAdminFilter.class})
    public SpringBootAdminFilter adminFilter() {
        if (logger.isInfoEnabled()) {
            logger.info("------------create an spring boot admin filter.------------");
        }
        return new SpringBootAdminFilter();
    }

    @Bean
    @ConditionalOnBean({SpringBootAdminFilter.class})
    public FilterRegistrationBean adminFilterRegister(SpringBootAdminProperties properties, SpringBootAdminFilter adminFilter) {
        if (logger.isInfoEnabled()) {
            logger.info("------------register an spring boot admin filter.------------");
        }
        FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(adminFilter);
        if (logger.isInfoEnabled()) {
            logger.info("------------spring boot admin filter listen url pattern: [" + properties.getUrlPattern() + "].--------------------");
        }
        registrationBean.addUrlPatterns(properties.getUrlPattern().split(","));
        if (logger.isInfoEnabled()) {
            logger.info("------------spring boot admin filter add supported address: [" + properties.getIpAddress() + "].--------------------");
        }
        registrationBean.addInitParameter(SpringBootAdminFilter.INCLUDE_ADDRESS, properties.getIpAddress());
        return registrationBean;
    }
}
